import pyodbc

class ConnectSqlServer:
    def __init__(self, server, database, use_windows_auth=True, user=None, password=None, driver='{ODBC Driver 17 for SQL Server}', port=1433):
        self.server = server
        self.database = database
        self.use_windows_auth = use_windows_auth
        self.user = user
        self.password = password
        self.driver = driver
        self.port = port

    def __enter__(self):
        if self.use_windows_auth:
            conn_str = (
                f'DRIVER={self.driver};SERVER={self.server},{self.port};'
                f'DATABASE={self.database};Trusted_Connection=yes;TrustServerCertificate=yes'
            )
        else:
            conn_str = (
                f'DRIVER={self.driver};SERVER={self.server},{self.port};'
                f'DATABASE={self.database};UID={self.user};PWD={self.password};TrustServerCertificate=yes'
            )
        self.conn = pyodbc.connect(conn_str)
        self.cursor = self.conn.cursor()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.conn.close()
\

def one_query(sql,
              server='楞次定律',
              database='supermr_db',
              use_windows_auth=True,
              user=None,
              password=None,
              driver='{ODBC Driver 17 for SQL Server}',
              port=1433):
    with ConnectSqlServer(server, database, use_windows_auth, user, password, driver, port) as db:
        db.cursor.execute(sql)
        try:
            return db.cursor.fetchall()
        except Exception:
            return []
def mult_query(sql_list,
               server='楞次定律',
               database='supermr_db',
               use_windows_auth=True,
               user=None,
               password=None,
               driver='{ODBC Driver 17 for SQL Server}',
               port=1433):
    with ConnectSqlServer(server, database, use_windows_auth, user, password, driver, port) as db:
        results = []
        for sql in sql_list:
            db.cursor.execute(sql)
            try:
                results.append(db.cursor.fetchall())
            except Exception:
                results.append([])
        return results
